package com.deep.seckill.schedule;

import com.deep.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 商品定时秒杀功能
 * <p>
 * 秒杀商品定时上架
 * 每天晚上3点，上架最近三天需要三天秒杀的商品
 * 当天00:00:00 - 23:59:59
 * 明天00:00:00 - 23:59:59
 * 后天00:00:00 - 23:59:59
 *
 * @author Deep
 * @date 2022/2/21
 */
@Slf4j
@Service
public class SeckillSkuScheduled {
    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    // 秒杀商品上架功能的锁
    private static final String upload_lock = "seckill:upload:lock";

    // 保证幂等性问题（在分布式情况下商品可能会被不同机器重复上架，解决方案：分布式锁）
//    @Scheduled(cron = "*/60 * * * * ? ") // 每5秒上架一次商品
    @Scheduled(cron = "0 0 3 * * ? ")
    public void uploadSeckillSkuLatest3Days() {
        // 1、重复上架无需处理
        log.info("上架秒杀的商品...");
        // 分布式锁
        RLock lock = redissonClient.getLock(upload_lock);
        try {
            // 加锁
            lock.lock(10, TimeUnit.SECONDS);
            seckillService.uploadSeckillSkuLatest3Days();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
